// 给你单链表的头指针head和两个整数left和right，其中left <= right，请你反转从位置left到right的链表节点，返回反转后的链表

// 思路：需要找到反转区间的前一个节点preNode和后一个节点tailNext，然后在这个区间反转后更新preNode和tailNext的指向
// 时间复杂度：O(n)
// 空间复杂度：O(1)

const { LinkedList, ListNode} = require('./64.设计链表')

function reverseBetween(head, left, right) {
    let dummyHead = new ListNode(0, head)
    let index = 0
    let cur = dummyHead
    let preNode = null
    let tailNext = null
    while (cur && index <= right + 1) {
        if (index === left - 1) {
            preNode = cur
        }
        if (index === right + 1) {
            tailNext = cur
        }
        cur = cur.next
        index++
    }
    reverse(preNode, tailNext)
    return dummyHead.next
}

function reverse(preNode, tailNext) {
    console.log('preNode, tailNext', preNode, tailNext)
    let pre = preNode
    let cur = preNode.next
    let firstNode = preNode.next
    let temp
    while (cur !== tailNext) {
        temp = cur.next
        cur.next = pre
        pre = cur
        cur = temp
    }
    preNode.next = pre
    firstNode.next = tailNext
}

// let head = [1, 2, 3, 4, 5], left = 1, right = 2
// let node = new LinkedList(head)
let head = [1], left = 1, right = 1
let node = new LinkedList(head)

console.log(reverseBetween(node.head, left, right));